package com.hice.demo.java.executor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Java 程序员都知道我们可以用 ScheduledExecutorService 按照一定的间隔或频率执行任务，
 * 但这个任务一旦开始，就只能到 ThreadPool shutdown 了才能结束。
 * 如何按照一定条件，在不终止整个线程池的情况下结束任务。
 *
 * @author hyson
 * @create 2017-03-06 17:10
 */
public class ConditionCancelScheduler {

    private static ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) throws Exception {
        final String jobID = "my_job_1";
        final AtomicInteger count = new AtomicInteger(0);
        final Map<String, Future> futures = new HashMap<>();

        final CountDownLatch countDownLatch = new CountDownLatch(1);
        Future future = scheduler.scheduleWithFixedDelay((Runnable) () -> {
            System.out.println(count.getAndIncrement());

            if (count.get() > 10) {
                Future future1 = futures.get(jobID);
                if (future1 != null) future1.cancel(true);
                countDownLatch.countDown();
            }
        }, 0, 1, TimeUnit.SECONDS);

        futures.put(jobID, future);
        countDownLatch.await();
        System.out.println("scheduler.scheduleWithFixedDelay 循环执行结束, scheduler准备关闭");
        scheduler.shutdown();
    }

}
